import os

import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from cfcall.etcdb import migration as mig
from cfcall.utils import osdistutils as osdist
from cfcall.utils import aptutils as apt

home = os.path.expanduser("~")
os.system('mkdir -p '+home+'/.cfcall')
engine = sqlalchemy.create_engine('sqlite:///'+home+'/.cfcall/distribution-cfg.db', echo=False)



"""--------------use declarative_base access Table--------------"""

Base = declarative_base()

class lsbPkgFileMd5(Base):
    __tablename__ = "lsb_pkg_file_Md5"
     
    id = Column(Integer, primary_key=True)
    dvendor = Column(String(32))  # ('Ubuntu', '12.04', 'precise'), a json
    dver = Column(String(32))  # ('Ubuntu', '12.04', 'precise'), a json
    dname = Column(String(32))  # ('Ubuntu', '12.04', 'precise'), a json
    
    pkg  = Column(String(128))  # full pkgname: ibus-pinyin-db-android_1.4.0-1_all.deb
    file = Column(String(256))  # full file path form root: /usr/share/ibus-pinyin/db/android.db
    md5sum = Column(String(128)) # 

"""Don't create it use declarative base, not support UniqueConstraint """
#Base.metadata.create_all(engine)  

"""----------------------------------------------"""
Session = sessionmaker(bind=engine)


def init_db():
    mig.create_table(engine)

def db_session():
    return Session()
   
def save_md5(session, pkg, fname, md5):
    
    e = lsbPkgFileMd5()
    
    dist = osdist.osdist()
    e.dvendor = dist[0]
    e.dver = dist[1]
    e.dname = dist[2]
    
    e.pkg = pkg
    e.file = fname
    e.md5sum = md5
    
    session.add(e)

def query_md5(session, pkg, fname):
    dist = osdist.osdist()
    for e in session.query(lsbPkgFileMd5).\
                filter_by(dvendor=dist[0]).\
                filter_by(dver=dist[1]).\
                filter_by(dname=dist[2]).\
                filter_by(pkg=pkg).\
                filter_by(file=fname).\
                all(): 
        return e.md5sum


def get_cached_md5(pkg, f):
    
    deb = apt.get_cached_deb_fname(pkg)
    session =  db_session()
    
    
    md5 = query_md5(session, deb, f)
    
    if md5 is None:
        # ensure the cache had the current pkg
        apt.download_pkg(pkg)
        
        # unpack to /tmp 
        apt.unpack_deb(deb)
        
        # calc md5 to check if file be modified.
        md5 = apt.calc_tmp_file_md5(f)
        save_md5(session, deb, f, md5)
        session.commit()
        print "saved %s md5:%s"%(deb, md5)
        return md5
    else:
        return md5



""" ---------------------------------------------------- """
def test_create_data():
    session =  db_session()
    save_md5(session, "test_1.4.0-1_all.deb",
                "android", "342342423423423234234")
    #save_md5(session, "test_1.4.0-1_all.deb",
    #           "android", "342342423423423234234")
    save_md5(session, "test_1.4.0-1_all.deb",
                "android.db", "342342423423423234234")
    
    session.commit()
    
    print query_md5(session,"test_1.4.0-1_all.deb", "android")
    
    for x in session.query(lsbPkgFileMd5).all(): 
        print x.dname, x.file, x.md5sum
        session.delete(x)
    session.commit()


""" Test"""
def _test():
    init_db()
    test_create_data()
